package com.nl.controller.web.service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.nl.controller.common.annotation.SystemServiceLog;
import com.nl.controller.common.service.CommonService;
import com.nl.controller.web.bean.SmsMgrGovernmentInfo;
import com.nl.controller.web.bean.TaskSynInfo;
import com.nl.controller.web.mapper.SmsInterfaceJzzwMapper;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class SmsInterfaceJzzwService {
	@Autowired
	private SmsInterfaceJzzwMapper smsInterfaceMapper;
	@Autowired
	private CommonService commonService;
	
	private final String interfaceUrl="http://10.32.42.77:10121/govSms/callback/smsTaskJobState";//接口地址
	/**
	 * desc:短信通道号同步接口
	 * @author syl
	 * @Date 2019年9月24日 下午2:07:42
	 * @param sendNumberSynReq
	 * @return
	 */
    @Transactional
	public Map<String, Object> sendNumberSyn(String sendNumberSynReq){
		Map<String,Object> map=new HashMap<String, Object>();
		String resultCode="-1";
        String resultDesc="";
        String streamSeq="";
        try {
        	JSONObject json = JSON.parseObject(sendNumberSynReq);
        	if(null!=json && !"".equals(json)){
        		log.info("【短信通道号同步接口】json：{}",json.toJSONString());
        		String sendNumber = json.getString("sendNumber");
        		//sendNumber = sendNumber.substring(8);//截取扩展码
				String cityId = json.getString("cityId");
        		String mgrName = json.getString("mgrName");
        		streamSeq = json.getString("streamSeq");
        		//1.判断项目名是否重复
        		int isExist = smsInterfaceMapper.getMgrIsExist(mgrName);
				if (isExist==0) {
					//2.封装入参
					SmsMgrGovernmentInfo smsMgrInfo = new SmsMgrGovernmentInfo();
					smsMgrInfo.setCityId(cityId);
					smsMgrInfo.setMgrName(mgrName);
					smsMgrInfo.setSendNumber(sendNumber);
					smsMgrInfo.setStreamSeq(streamSeq);
					//3.将获取的接口信息插入项目表
					smsInterfaceMapper.addMgrGovernment(smsMgrInfo);
			        resultCode = "0";
                    resultDesc = "【短信通道号同步接口】调用成功";
				}else {
					log.info("【短信通道号同步接口】项目名称已存在");
					resultDesc = "【短信通道号同步接口】项目名称重复";
				}
        	}else {
        		resultDesc = "【短信通道号同步接口】未获取到需要同步的信息";
			}
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			resultDesc="【短信通道号同步接口】异常,error:"+e.getMessage();
			e.printStackTrace();
			log.info("调用【短信通道号同步接口】失败");
		}
        map.put("resultCode", resultCode);
	  	map.put("resultDesc", resultDesc);
	  	map.put("streamSeq", streamSeq);
		return map;
	}
    /**
     * desc:短信任务同步接口
     * @author syl
     * @Date 2019年9月25日 下午5:22:30
     * @param taskSynReq
     * @return
     */
    @Transactional
    public Map<String, Object> taskSyn(String taskSynReq){
    	Map<String,Object> map=new HashMap<String, Object>();
		String resultCode="-1";
        String resultDesc="";
        String streamSeq="";
        try {
        	JSONObject json = JSON.parseObject(taskSynReq);
        	if(null!=json && !"".equals(json)){
        		log.info("【短信任务同步接口】json：{}",json.toJSONString());
        		String ops = json.getString("ops")==null?"":json.getString("ops");
        		String sendNumber = json.getString("sendNumber")==null?"":json.getString("sendNumber");
        		String taskId = json.getString("taskId")==null?"":json.getString("taskId");
        		String taskName = json.getString("taskName")==null?"":json.getString("taskName");
        		String sendContent = json.getString("sendContent")==null?"":json.getString("sendContent");
        		String taskStatus = json.getString("taskStatus")==null?"":json.getString("taskStatus");
        		String taskStart = json.getString("taskStart")==null?"":json.getString("taskStart");
        		String taskEnd = json.getString("taskEnd")==null?"":json.getString("taskEnd");
        		streamSeq = json.getString("streamSeq")==null?"":json.getString("streamSeq");
        		String cityId = sendNumber.substring(8, 10);
        		cityId = cityId==null?"":cityId;
        		TaskSynInfo taskSynInfo = new TaskSynInfo();
        		taskSynInfo.setSendNumber(sendNumber);
        		taskSynInfo.setTaskId(taskId);
        		taskSynInfo.setTaskName(taskName);
        		taskSynInfo.setSendContent(sendContent);
        		taskSynInfo.setTaskStatus(taskStatus);
        		taskSynInfo.setTaskStart(taskStart);
        		taskSynInfo.setTaskEnd(taskEnd);
        		taskSynInfo.setCityId(cityId);
        		taskSynInfo.setStreamSeq(streamSeq);
        		//判断操作类型
        		if ("1".equals(ops)) {//新增
        			//判断是否已有新增任务
        			int judge = smsInterfaceMapper.judgeTaskInfo(taskId);
        			if (judge==0) {
        				smsInterfaceMapper.addTaskInfo(taskSynInfo);
    					log.info("【短信任务同步接口】新增短信任务："+taskSynInfo.getTaskId()+","+taskSynInfo.getTaskName());
    					//短信内容新增或改变时，插入精准政务待发表
    					if (!"".equals(taskSynInfo.getSendContent())) {
    						this.insertSend(taskSynInfo,ops);
						}
    					resultCode = "0";
    	                resultDesc = "【短信任务同步接口】新增成功";
					}else {
						resultDesc = "【短信任务同步接口】此任务已存在，新增失败";
					}
				}else if ("2".equals(ops)) {//修改
					int flag = smsInterfaceMapper.updateTaskInfo(taskSynInfo);
					log.info("【短信任务同步接口】修改短信任务："+taskSynInfo.getTaskId()+","+taskSynInfo.getTaskName());
					if (!"".equals(taskSynInfo.getSendContent())) {
						this.insertSend(taskSynInfo,ops);
					}
					if (flag==1) {
						resultCode = "0";
		                resultDesc = "【短信任务同步接口】修改成功";
					}else{
						resultDesc = "【短信任务同步接口】修改失败";
					}
				}else {
					resultDesc = "【短信任务同步接口】未获取到操作类型";
				}
        	}else {
        		resultDesc = "【短信任务同步接口】未获取到需要同步的信息";
			}
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			resultDesc="【短信任务同步接口】异常,error:"+e.getMessage();
			e.printStackTrace();
			log.info("调用【短信任务同步接口】失败");
		}
		map.put("resultCode", resultCode);
	  	map.put("resultDesc", resultDesc);
	  	map.put("streamSeq", streamSeq);
		return map;
    }
    private void insertSend(TaskSynInfo taskSynInfo,String ops){
    	Map<String, Object> map = null;
    	String option = "";
    	String[] msisdns = commonService.templateNotice("1000000002");
    	for (int i = 0; i < msisdns.length; i++) {
			if (null!=msisdns[i] && !"".equals(msisdns[i])) {
				map = new HashMap<String, Object>();
				map.put("receiver", msisdns[i]);
				map.put("sender", "10657016");
				map.put("result", -1);
				map.put("cityId", taskSynInfo.getCityId());
				map.put("mgrId", taskSynInfo.getTaskId());
				map.put("mgrName", taskSynInfo.getTaskName());
				String sendNumber = taskSynInfo.getSendNumber();
				map.put("cityExtId", sendNumber.substring(sendNumber.length()-6, sendNumber.length()));
				if ("1".equals(ops)) {
					option = "新增";
				}else if ("2".equals(ops)) {
					option = "修改";
				}
				String content = "【精准政务】"+option+"操作，项目名称："+taskSynInfo.getTaskName()+"，短信内容："+taskSynInfo.getSendContent()
							+" 请审核(同意请回复Y-"+taskSynInfo.getTaskId()+"-BQ，不同意请回复N-"+taskSynInfo.getTaskId()+"-BQ)";
				log.info("【短信任务同步接口】插入精准政务待发表,content:"+content);
				map.put("content", content);
				smsInterfaceMapper.addSendInfo(map);
			}
		}
    }
    /**
     * desc:审核结果同步接口
     * @author syl
     * @Date 2019年9月26日 下午3:12:53
     * @param json
     * @return
     */
//    @SystemServiceLog(description = "审核结果同步接口", value = false)
	public HashMap<String, Object> checkResultSyn(com.alibaba.fastjson.JSONObject json){
		HashMap<String,Object> map=new HashMap<String, Object>();
        String retCode="-1";
        String retMsg="";
        JSONObject req = new JSONObject();
        String resp="";
        try {
          	req=this.initCheckResultSynReq(json);
          	resp=this.httpPostWithJSON(interfaceUrl, req); 
//          	resp = "{\"resultCode\":\"0\",\"resultDesc\":\"成功\",\"streamSeq\":\"20190809110306100001\"}";
          	log.info("审核返回报文:"+resp);
          	map=this.readCheckResultSynResp(resp);
          	log.info("审核报文解析:"+map);
        } catch (Exception e){
			retMsg="【审核结果同步接口】异常,error:"+e.getMessage();
			map.put("resultCode", retCode);
		  	map.put("resultDesc", retMsg);
			e.printStackTrace();
		}
  	  	return map;
    }
    /**
     * desc:初始化审核结果同步接口请求报文
     * @author syl
     * @Date 2019年9月26日 下午3:15:40
     * @param parm
     * @return
     */
    private JSONObject initCheckResultSynReq(JSONObject parm){
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
    	parm.put("streamSeq", sdf.format(new Date())+this.getSeq());
    	return parm;
    }
    /**
     * desc:解析审核结果同步接口返回报文
     * @author syl
     * @Date 2019年9月26日 下午3:44:55
     * @param resp
     * @return
     */
    private HashMap<String, Object> readCheckResultSynResp(String resp){
        String retCode="-1";
        HashMap<String, Object> retMap=new HashMap<String, Object>();
        if(resp!=null&&!"".equals(resp)){
        	JSONObject jsonObject=JSONObject.parseObject(resp);
            retMap.put("resultCode", jsonObject.getString("resultCode"));
            retMap.put("resultDesc", jsonObject.getString("resultDesc"));
            retMap.put("streamSeq", jsonObject.getString("streamSeq"));
        }else {
        	retMap.put("resultCode", retCode);
        	retMap.put("resultDesc", "【审核结果同步接口】未获取到返回报文");
		}
        return retMap;
    }
    /**
     * desc:获取序列号
     * @author syl
     * @Date 2019年9月26日 下午3:15:06
     * @return
     */
	public String getSeq()  {
		String seq="";
		try {
			seq = smsInterfaceMapper.getInterfaceSeq();
		} catch (Exception e) {
			e.printStackTrace();
            log.error("获取序列号");
		}
		return seq;
	}
	public String httpPostWithJSON(String url, JSONObject jsonParam)
            throws Exception {
        DefaultHttpClient httpclient = null;
        HttpPost httpPost = null;
        HttpResponse response = null;
        org.apache.http.HttpEntity entity = null;
        String result = "";
        try {
            httpclient = new DefaultHttpClient();
            httpPost = new HttpPost(url);
            StringEntity entityParam = new StringEntity(jsonParam.toString(),
                    "utf-8");// 解决中文乱码问题
            entityParam.setContentEncoding("UTF-8");
            entityParam.setContentType("application/json");
            httpPost.setEntity(entityParam);
            // 设置连接超时时间
            HttpConnectionParams.setConnectionTimeout(httpclient.getParams(),
                    100000);
            // 设置读数据超时时间
            HttpConnectionParams.setSoTimeout(httpclient.getParams(), 100000);
            response = httpclient.execute(httpPost);
            entity = response.getEntity();
            if (null != entity) {
                byte[] bytes = EntityUtils.toByteArray(entity);
                result = new String(bytes, "UTF-8");
            } 
            return result;
        } catch (Exception e) {
            throw e;
        } finally {
            if (null != httpclient) {
                httpclient.getConnectionManager().shutdown();
            }
        }
    }
}
